# _*_ coding:utf-8 _*_
import os
import sys
import time
import unittest
from API.config import setting
from API.del_report.del_report import del_report
from API.lib.gethtml import get_htmlvalues
from API.lib.newreport import new_report
from API.lib.sendmail import send_mail
from API.package.HTMLTestRunnerone import HTMLTestRunner

sys.path.append(os.path.dirname(__file__))  # window环境适配的代码


# sys.path.append(os.path.abspath('..'))# linux环境适配的代码

def add_case(test_path=setting.Test_Case):
    """
         加载所有的测试用例
         :param test_path:加载用例的路径
         :return: 返回测试套件
    """
    # print(f"当前工作目录: {os.getcwd()}")
    # print(f"测试路径: {test_path}")
    # print(f"系统路径: {sys.path}")
    # 批量调用setting.Test_Case路径下的文件，返回一个测试套件
    discover = unittest.defaultTestLoader.discover(test_path, pattern='test*.py')
    # print(f"加载的测试套件: {discover}")
    return discover


def run_case(all_case, result_path=setting.Test_Report):
    """
         执行所有的测试用例
         :param all_case:测试套件
         :param result_path：生成报告保存路径
         :return: 无
    """
    now = time.strftime("%Y-%m-%d %H_%M_%S")
    filename = result_path + '/' + now + 'result.html'
    fp = open(filename, 'wb')
    runner = HTMLTestRunner(stream=fp, title='轻诉App接口自动化测试报告', description=u"轻诉App接口用例测试情况",
                            tester='归乐'
                            )
    runner.run(all_case)
    fp.close()

    # 发送邮件
    report = new_report(setting.Test_Report)
    result = get_htmlvalues(report)
    if "100.00%" not in result:
        send_mail(report)
    del_report()


if __name__ == "__main__":
    cases = add_case()
    run_case(cases)
